const express = require('express');
const XLSX = require('xlsx');
const bodyParser = require('body-parser');
const path = require('path');

const app = express();
const port = 4000;

app.use(bodyParser.json());
app.use(express.static(path.join(__dirname, 'public')));

// 读取 Excel 文件并解析特定的工作表
function readSheet(file, sheetName) {
  return new Promise((resolve, reject) => {
    try {
      const workbook = XLSX.readFile(file);
      const worksheet = workbook.Sheets[sheetName];
      const data = XLSX.utils.sheet_to_json(worksheet);
      resolve(data);
    } catch (error) {
      reject(error);
    }
  });
}

// 筛选职位
// function filterPositions(positions, criteria) {
//   return positions.filter((position) => {
//     return Object.keys(criteria).every((key) => {
//       return String(position[key]).toLowerCase().includes(String(criteria[key]).toLowerCase());
//     });
//   });
// }
// 筛选职位
// function filterPositions(positions, criteria) {
//   return positions.filter((position) => {
//     return (criteria.department.length === 0 || criteria.department.includes(position.department)) &&
//            (criteria.location.length === 0 || criteria.location.includes(position.location));
//   });
// }

// function filterPositions(positions, criteria) {
//   return positions.filter((position) => {
//     return Object.keys(criteria).every((key) => {
//       if (Array.isArray(criteria[key])) {
//         return criteria[key].some((value) => String(position[key]).toLowerCase().includes(String(value).toLowerCase()));
//       } else {
//         return String(position[key]).toLowerCase().includes(String(criteria[key]).toLowerCase());
//       }
//     });
//   });
// }
// function filterPositions(positions, criteria) {
//   return positions.filter((position) => {
//     // 检查是否有任何一个条件满足
//     return Object.keys(criteria).some((key) => {
//       if (Array.isArray(criteria[key])) {
//         return criteria[key].some((value) => String(position[key]).toLowerCase().includes(String(value).toLowerCase()));
//       } else {
//         return String(position[key]).toLowerCase().includes(String(criteria[key]).toLowerCase());
//       }
//     });
//   });
// }
function filterPositions(positions, criteria) {
  return positions.filter((position) => {
    return Object.keys(criteria).every((key) => {
      // if (key === 'paichu') {
      //   const criteria_paichu = criteria[key];
      //   //     // 检查是否有任何一个条件满足
      //   return Object.keys(criteria_paichu).some((key) => {

      //     if (Array.isArray(criteria_paichu[key]) && criteria_paichu[key].length) {
      //       return criteria_paichu[key].every((value) => !String(position[key]).toLowerCase().includes(String(value).toLowerCase()));
      //     } else {
      //       return !String(position[key]).toLowerCase().includes(String(criteria[key]).toLowerCase());
      //     }
      //   });
      // }
      // if (String(position[key]) === '') {
      //   return true;
      // }
      if (Array.isArray(criteria[key]) && criteria[key].length) {
        return criteria[key].some((value) => {
          return (String(value) === '空白' && String(position[key]) === '') ||
          (String(position[key]).toLowerCase().includes(String(value).toLowerCase()))
        });
      } else {
        return String(position[key]).toLowerCase().includes(String(criteria[key]).toLowerCase());
      }
    });
  });
}
function filterPaichu(positions, criteria_paichu) {
  return positions.filter((position) => {
    return Object.keys(criteria_paichu).every((key) => {
      if (Array.isArray(criteria_paichu[key]) && criteria_paichu[key].length) {
        return criteria_paichu[key].every((value) => !String(position[key]).toLowerCase().includes(String(value).toLowerCase()));
      }
    });
  });
}
// 筛选职位（所有条件都必须同时满足，但每个条件中的字段值如果是数组，只需要满足数组中的一个条件即可）
// function filterPositions(positions, criteria) {
//   return positions.filter((position) => {
//     // 检查所有条件是否都满足
//     return Object.keys(criteria).every((key) => {
//       if (Array.isArray(criteria[key])) {
//         return criteria[key].some((value) => String(position[key]).toLowerCase().includes(String(value).toLowerCase()));
//       } else {
//         return String(position[key]).toLowerCase().includes(String(criteria[key]).toLowerCase());
//       }
//     });
//   });
// }

function filterPositionsForBaoming(filteredPositions, baomings) {
  return filteredPositions.map(position => {
    const positionKey = position['招考职位由招录机关编报，招录专业、学历等与职位资格条件相关的问题，由招录机关负责解释。'] + '_' + position['__EMPTY_7'];
    if (baomings[positionKey]) {
      position.baokaorenshu = baomings[positionKey]['报考人数'];
      position.guoshenrenshu = baomings[positionKey]['过审人数'];
      position.jingzhengbi = baomings[positionKey]['竞争比'];
    }
    return position;
  });
}

async function readBaoming() {
  const file = path.join(__dirname, '111.xlsx');
  const sheetName = 'Sheet1'; // 你需要读取的工作表名称
  const positions = await readSheet(file, sheetName);
  return positions;
}

// API 接口
app.post('/api/positions', async (req, res) => {
  try {
    const file = path.join(__dirname, '222.xls');
    // const sheetName = '中央党群机关'; // 你需要读取的工作表名称
    const { dengji, qita, paichu } = req.body;
    const positions = await readSheet(file, dengji);

    let filteredPositions = filterPositions(positions, qita);
    filteredPositions = filterPaichu(filteredPositions, paichu)
    const baomings = await readBaoming();
    const obj = baomings.reduce((acc, item) => {
      // acc[item['招考职位由招录机关编报，招录专业、学历等与职位资格条件相关的问题，由招录机关负责解释。'] + '_' + item['__EMPTY_7']] = item;
      acc[item['部门代码'] + '_' + item['职位代码']] = item;
      return acc;
    }, {});
    const result = await filterPositionsForBaoming(filteredPositions, obj);
    res.json(result);
  } catch (error) {
    res.status(500).json({ error: '读取文件或筛选职位时发生错误' });
  }
});

app.get('/', (req, res) => {
  res.sendFile(path.join(__dirname, 'public', 'index.html'));
});

app.get('/guokao', (req, res) => {
  res.sendFile(path.join(__dirname, 'public', 'guokao.html'));
});

app.get('/sdsk', (req, res) => {
  res.sendFile(path.join(__dirname, 'public', 'sdsk.html'));
});

app.get('/scsk', (req, res) => {
  res.sendFile(path.join(__dirname, 'public', 'scsk.html'));
});

app.get('/jdwz202511', (req, res) => {
  res.sendFile(path.join(__dirname, 'public', 'jdwz202511.html'));
});

app.post('/api/jdwz202511', async (req, res) => {
  try {
    console.log(11111)
    const file = path.join(__dirname, './jdwz2025/111.xlsx');
    // const sheetName = '中央党群机关'; // 你需要读取的工作表名称
    const { dengji, qita, paichu } = req.body;
    const positions = await readSheet(file, dengji);
    console.log(positions)
    let filteredPositions = filterPositions(positions, qita);
    filteredPositions = filterPaichu(filteredPositions, paichu)
    // const baomings = await readBaoming();
    // const obj = baomings.reduce((acc, item) => {
    //   // acc[item['招考职位由招录机关编报，招录专业、学历等与职位资格条件相关的问题，由招录机关负责解释。'] + '_' + item['__EMPTY_7']] = item;
    //   acc[item['部门代码'] + '_' + item['职位代码']] = item;
    //   return acc;
    // }, {});
    // const result = await filterPositionsForBaoming(filteredPositions, obj);
    // res.json(result);
    res.json(filteredPositions);
  } catch (error) {
    res.status(500).json({ error: '读取文件或筛选职位时发生错误' });
  }
});

app.post('/api/scsk', async (req, res) => {
  try {
    const file = path.join(__dirname, './scsk2025/scsk.xlsx');
    // const sheetName = '中央党群机关'; // 你需要读取的工作表名称
    const { dengji, qita, paichu } = req.body;
    const positions = await readSheet(file, dengji);

    let filteredPositions = filterPositions(positions, qita);
    // filteredPositions = filterPaichu(filteredPositions, paichu)
    // const baomings = await readBaoming();
    // const obj = baomings.reduce((acc, item) => {
    //   // acc[item['招考职位由招录机关编报，招录专业、学历等与职位资格条件相关的问题，由招录机关负责解释。'] + '_' + item['__EMPTY_7']] = item;
    //   acc[item['部门代码'] + '_' + item['职位代码']] = item;
    //   return acc;
    // }, {});
    // const result = await filterPositionsForBaoming(filteredPositions, obj);
    // res.json(result);
    res.json(filteredPositions);
  } catch (error) {
    res.status(500).json({ error: '读取文件或筛选职位时发生错误' });
  }
});

app.post('/api/sdsk', async (req, res) => {
  try {
    const file = path.join(__dirname, './sdsk2025/sdsk.xls');
    // const sheetName = '中央党群机关'; // 你需要读取的工作表名称
    const { dengji, qita, paichu } = req.body;
    const positions = await readSheet(file, dengji);

    let filteredPositions = filterPositions(positions, qita);
    // filteredPositions = filterPaichu(filteredPositions, paichu)
    // const baomings = await readBaoming();
    // const obj = baomings.reduce((acc, item) => {
    //   // acc[item['招考职位由招录机关编报，招录专业、学历等与职位资格条件相关的问题，由招录机关负责解释。'] + '_' + item['__EMPTY_7']] = item;
    //   acc[item['部门代码'] + '_' + item['职位代码']] = item;
    //   return acc;
    // }, {});
    // const result = await filterPositionsForBaoming(filteredPositions, obj);
    // res.json(result);
    res.json(filteredPositions);
  } catch (error) {
    res.status(500).json({ error: '读取文件或筛选职位时发生错误' });
  }
});

// 启动服务器
app.listen(port, () => {
  console.log(`Server is running on http://localhost:${port}`);
});